package com.itstherules.jmsunit.expectation.xml.comparison;

import java.io.IOException;

import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.xml.sax.SAXException;

import com.itstherules.jmsunit.expectation.StringExpectation;


public abstract class BaseXmlExpectation implements StringExpectation {

	private final String expected;
	private final DiffQuestion question;

	public BaseXmlExpectation(String expected, DiffQuestion question) {
		if (expected == null) {
			throw new IllegalArgumentException("The expected value cannot be null");
		}
		this.question = question;
		this.expected = expected;
	}

	public final void compute(String actual) throws AssertionError {
		try {
			XMLUnit.setIgnoreWhitespace(true);
			Diff diff = XMLUnit.compareXML(expected, actual);
			if(!question.answer(diff)) {
				throw new AssertionError("XML Comparison Failed: " + diff.toString());
			}
		} 
		catch (IOException e) { throw new AssertionError(e); }
		catch (SAXException e) { throw new AssertionError(e); }
	}

	@Override
	public String toString() {
		return "Xml equals expectation (expected " + expected + ")";
	}
}
